package uit.shoeshop.dao;
import uit.shoeshop.dto.UserDTO;
import uit.shoeshop.lib.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
	private Connection conn;
	private String tableName;
	
	public UserDAO(){
		setConn(null);
		setTableName(Constants.TBL_USER);
	}

	public UserDTO getUser(String username,String password) throws SQLException{
		UserDTO results = new UserDTO();
		
		try{
			setConn(Util.Connect());
			String sql = "SELECT * FROM " + getTableName() + " WHERE username = ? AND password = ?";
			PreparedStatement stm = getConn().prepareStatement(sql);
		
			//gan gia tri cho cau sql
			stm.setString(1, username);
			stm.setString(2, Util.MD5(password));
			
			//thuc hien cau lenh sql
			ResultSet rs = stm.executeQuery();
			int check = 0;
			while (rs.next()) {
				results.setUser_id(rs.getInt("user_id"));
				results.setUsername(rs.getString("username"));
				results.setType(rs.getInt("type"));
				check = 1;
			}
			if(check == 0) results = null;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(getConn() != null)
				getConn().close();
		}
		return results;
	}	
	
	/**
	 * @param conn the conn to set
	 */
	public void setConn(Connection conn) {
		this.conn = conn;
	}

	/**
	 * @return the conn
	 */
	public Connection getConn() {
		return conn;
	}

	/**
	 * @param tableName the tableName to set
	 */
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	/**
	 * @return the tableName
	 */
	public String getTableName() {
		return tableName;
	}

}
